<?php

namespace XWAM\Model;

/**
 * Smtp 模型类
 *
 * @since 1.0 <2015-10-22> SoChishun <14507247@qq.com> Added.
 * @since 2.0 2017-3-20 SoChishun 由Document重命名为Smtp.
 */
class SmtpModel extends AppbaseModel {

    protected $tableName = 't_porg_sys_smtp';

    function saveSmtp() {
        $rules = array(
            array('title', 'require', '标题无效!', self::MUST_VALIDATE, 'regex', self::MODEL_INSERT),
            array('category_id', 'number', '类别无效!', self::EXISTS_VALIDATE, 'regex', self::MODEL_BOTH),
            array('user_name', 'require', '用户无效!', self::EXISTS_VALIDATE, 'regex', self::MODEL_BOTH),
            array('site_id', 'number', 'SiteID无效!', self::EXISTS_VALIDATE, 'regex', self::MODEL_BOTH),
        );
        if (!$this->validate($rules)->create()) {
            return $this->returnMsg(false, $this->getError());
        }
        //图片上传
        $msg = \Common\Controller\UploadHandlerController::upload(array('savePath' => 'Smtp/', 'skipEmpty' => true));
        if (is_array($msg) && isset($msg['picture_url'])) {
            $this->data['picture_url'] = $msg['picture_url']['filepath'];
        }
        if (isset($this->data['create_time']) && empty($this->data['create_time'])) {
            unset($this->data['create_time']);
        }
        $categoryId = empty($this->data['category_id']) ? false : $this->data['category_id'];
        if (empty($this->id)) {
            unset($this->data['id']);
            $result = $this->add();
        } else {
            $id = $this->id;
            $result = $this->save();
        }
        if ($categoryId) {
            SmtpCategoryModel::updateForeignTitle(false, $categoryId);
        }
        return $this->returnMsg($result);
    }

    function changeStatus($id, $status) {
        $result = $this->where(array('id' => $id))->setField(array('status' => $status));
        return $this->returnMsg($result);
    }

    function changeSort($id, $sort) {
        $result = $this->where(array('id' => $id))->setField(array('sort' => $sort));
        return $this->returnMsg($result);
    }

    function deleteSmtp($id) {
        $result = $this->delete($id);
        return $this->returnMsg($result);
    }

    function saveCategory($aid, $aCategoryId) {
        $table = $this->tableName;
        $sqls = array();
        $upIds = array();
        $i = 0;
        foreach ($aCategoryId as $categoryId) {
            $id = $aid[$i];
            if ($categoryId) {
                $upIds[] = $categoryId;
                $sqls[] = "update $table set category_id=$categoryId where id=$id";
            }
            $i++;
        }
        if (!$sqls) {
            return $this->returnMsg(false, '未选择类别!');
        }
        $mAdv = new \Think\Model\AdvModel();
        $mAdv->patchQuery($sqls);
        SmtpCategoryModel::updateForeignTitle(false, implode(',', $upIds));
        return $this->returnMsg(true);
    }

    // 2017-3-24
    public function Send($id, $data) {
        $smtp = $this->find($id);
        if (!$smtp) {
            return $this->returnMsg(false, 'SMTP服务器不存在!');
        }
        Vendor('PHPMailer.PHPMailerAutoload');
        $mail = new PHPMailer(); //实例化
        $mail->IsSMTP(); // 启用SMTP
        $mail->Host = $smtp['host']; //smtp服务器的名称（这里以QQ邮箱为例）
        $mail->SMTPAuth = $smtp['smtp_auth']; //启用smtp认证
        $mail->Username = $smtp['login_id']; //你的邮箱名
        $mail->Password = $smtp['password']; //邮箱密码
        $mail->From = $smtp['from_address']; //发件人地址（也就是你的邮箱地址）
        $mail->FromName = $smtp['from_name']; //发件人姓名
        $mail->AddAddress($data['to_address'], "尊敬的客户");
        $mail->WordWrap = 50; //设置每行字符长度
        $mail->IsHTML(false); // 是否HTML格式邮件
        $mail->CharSet = 'utf-8'; //设置邮件编码
        $mail->Subject = $data['subject']; //邮件主题
        $mail->Body = $data['body']; //邮件内容
        $mail->AltBody = "这是一个纯文本的身体在非营利的HTML电子邮件客户端"; //邮件正文不支持HTML的备用显示
        return($mail->Send());
    }

}
